MyApp.module("LoginModule", function (LoginModule, MyApp, Backbone, Marionette, $, _) {


    //Attributes
	LoginModule.startWithParent = false;
	LoginModule.view = new LoginView();
	LoginModule.region = null;
	
    //Initializer & Finalizer
	MyApp.module('LoginModule').on('start', function (region) {
        console.log("LoginModule:on:start start...")
	    this.region = region;
        this.region.show(this.view);
        console.log("LoginModule:on:start stop...")
	});
	
	LoginModule.addInitializer(function(){
	    
	});
	
	LoginModule.addFinalizer(function () {
	    this.region.close();
	    this.view = null;
	    this.region = null;
	});
	
	//Functions
	LoginModule.login = function(user){

        user.fetch({
            data: {
                email: user.get('email'),
                password: user.get('password'),
                sessionId: user.get('sessionId'),
                type: "Login User"
            },
            success: function(data){
                if(user.get('type') === 'Success'){
                    writeCookie('sessionId', user.get('sessionId'), 3);
                    MyApp.user = user;
                    isLoggedIn = true;
                    document.location.href = websiteUrl + '#/default';
                }else{
                    alert('Username or Password incorrect');
                }
            },

            error: function(data){
                console.log("Couldn't reach Server for login.");
            }
        });
        /*
        var xmlhttp;
        xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange=function(){
            if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {
                console.log("OKOK");
            }
        }
        xmlhttp.open("GET", webserviceUrl + authUrl + '{"email": "marius.widmann@gmail.com","password": "password","surname": "Widmann","name": "Marius","type": "Login User","points": 0}', true);
        xmlhttp.send();
        console.log(marius.name);
        */

	};

	
});

//Module Subscribers
MyApp.module('LoginModule').on('LoginView:login', function(email, password, sessionId){
    MyApp.user.set('email', email);
    MyApp.user.set('password', password);
    MyApp.user.set('sessionId', sessionId);
	this.login(MyApp.user);
});